package com.ruoyi.common.utils;

import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * @author chmj
 * @version V1.0
 * @Package com.hb.project.connect.util
 * @Copyright 2021/7/21 12:10 汇博医疗股份有限公司
 */
public class HttpOutSideUtil {

    private static final int TIMOUT = 5000;

    /**
     * 请求设置
     * @return
     */
    private static RequestConfig requestConfig(){
        return RequestConfig.custom().setConnectTimeout(TIMOUT) //连接超时
                .setConnectionRequestTimeout(TIMOUT)//请求超时
                .setSocketTimeout(TIMOUT)
                .setRedirectsEnabled(true)  //允许自动重定向
                .build();
    }

    /**
     * 封装get发送数据
     * @return
     */
    public static String getByHttp(String url, Map<String,String> map) {
        String result = null;
        CloseableHttpClient httpClient = HttpClients.createDefault();
        Set<Map.Entry<String,String>> entries=map.entrySet();
        url += "?";
        for (Map.Entry entry:entries){
            url = url + entry.getKey() + "=" + entry.getValue() + "&";
        }
        HttpGet httpGet = new HttpGet(url.substring(0,url.length() - 1));
        httpGet.setConfig(requestConfig());
        try{
            HttpResponse httpResponse = httpClient.execute(httpGet);
            if(httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
                result = EntityUtils.toString( httpResponse.getEntity());
//                String jsonResult = EntityUtils.toString( httpResponse.getEntity());
//                result = new String(jsonResult.getBytes("ISO8859-1"),charset);
                Map<String,Object> hMap = JSONObject.parseObject(result,Map.class);
                if ("200".equals(hMap.get("code").toString()) && hMap.containsKey("data")) {
                    result = hMap.get("data").toString();
                } else {
                    result = null;
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            try {
                httpClient.close();
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        return result;
    }

    /**
     * 封装post发送数据
     * @return
     */
    public static String postByHttps(String url, Map<String,String> map, String charset) {
//        Map<String,Object> resultMap = new HashMap<>();
        HttpClient httpClient = null;
        HttpPost httpPost = null;
        String result = null;
        try{
            httpClient = new SSLClient();
            httpPost = new HttpPost(url);
            //设置参数
            List<NameValuePair> list = new ArrayList<NameValuePair>();
            Iterator iterator = map.entrySet().iterator();
            while(iterator.hasNext()){
                Map.Entry<String,String> elem = (Map.Entry<String, String>) iterator.next();
                list.add(new BasicNameValuePair(elem.getKey(),elem.getValue()));
            }
            if(list.size() > 0){
                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list,charset);
                httpPost.setEntity(entity);
            }
            HttpResponse response = httpClient.execute(httpPost);
            if(response != null){
                HttpEntity resEntity = response.getEntity();
                if(resEntity != null){
                    result = EntityUtils.toString(resEntity,charset);
//                    resultMap = JsonUtil.string2Obj(result,Map.class);
                }
            }
        }catch(Exception ex){
            ex.printStackTrace();
        }
//        return resultMap;
        return result;
    }

    /**
     * 封装post发送json数据
     * @return
     */
    public static String doPostJson(String url, String json){
        String result = null;
        //第一步：创建HttpClient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        //第二步：创建httpPost对象
        HttpPost httpPost = new HttpPost(url);
        httpPost.setConfig(requestConfig());
        //第三步：给httpPost设置JSON格式的参数
        StringEntity entity = new StringEntity(json,"utf-8");
        entity.setContentEncoding("UTF-8");
        httpPost.setHeader("Content-type", "application/json");
        httpPost.setEntity(entity);
        //第四步：发送HttpPost请求，获取返回值
        HttpResponse res = null;
        try {
            res = httpClient.execute(httpPost);
            if(res.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
                result = EntityUtils.toString(res.getEntity());// 返回json格式：
                Map<String,Object> hMap = JSONObject.parseObject(result,Map.class);
                if ("200".equals(hMap.get("code").toString()) && hMap.containsKey("data")) {
                    result = hMap.get("data").toString();
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try{
                httpClient.close();
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        return result;
    }
}
